﻿using System;
using System.Web.Caching;
using BoldBrick.OneIntranet.HR.Properties;

namespace BoldBrick.CSOB.Intranet.Utils
{
	public static class CacheHelper
	{
		/// <summary>
		/// This method sets value to the cache with expiration from web.config
		/// </summary>
		/// <param name="key">Key of the value</param>
		/// <param name="value">The value</param>
		public static void TrySet(string key, object value)
		{
			TrySet(key, value, false);
		}

		/// <summary>
		/// This method sets value to the cache with expiration from web.config if <paramref name="noExpiration"/> is set to false
		/// </summary>
		/// <param name="key">Key of the value</param>
		/// <param name="value">The value</param>
		/// <param name="noExpiration">If true, value has no expiration, otherwise value has expiration from web.config</param>
		public static void TrySet(string key, object value, bool noExpiration)
		{
			if (noExpiration)
			{
				SharePoint.CommonControls.Utils.CacheHelper.Set(
					key, value,
					Cache.NoAbsoluteExpiration,
					Cache.NoSlidingExpiration,
					CacheItemPriority.Normal);
				return;
			}
			
			int customCachingInterval = Settings.Default.CustomCachingIntervalMinutes;
			if (customCachingInterval <= 0)
				return;
			
			SharePoint.CommonControls.Utils.CacheHelper.Set(
				key, value,
				DateTime.Now.AddMinutes(customCachingInterval),
				Cache.NoSlidingExpiration,
				CacheItemPriority.Normal);
		}

		/// <summary>
		/// Gets value fromthe cache
		/// </summary>
		/// <typeparam name="TType">Type of the value</typeparam>
		/// <param name="key">Key of the value</param>
		/// <returns>Returns value fromthe cache</returns>
		public static TType Get<TType>(string key)
		{
			return SharePoint.CommonControls.Utils.CacheHelper.Get<TType>(key);
		}
	}
}
